<!DOCTYPE composition PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
	xmlns:s="http://jboss.org/schema/seam/taglib"
	xmlns:ui="http://java.sun.com/jsf/facelets"
	xmlns:f="http://java.sun.com/jsf/core"
	xmlns:h="http://java.sun.com/jsf/html"
	xmlns:p="http://primefaces.org/ui" 
	template="/layout/templateUser.xhtml">

	<ui:define name="head">
		<script type="text/javascript"
			src="//maps.google.com/maps/api/js?sensor=true"></script>

		<script type="text/javascript">
		  var idFace;
		  var deficiency;
    	  window.fbAsyncInit = function() {
    	  FB.init({
    	    appId      : '185409784868940',
    	    status     : true, // check login status
    	    cookie     : true, // enable cookies to allow the server to access the session
    	    xfbml      : true  // parse XFBML
    	  });

    	  // Here we subscribe to the auth.authResponseChange JavaScript event. This event is fired
    	  // for any authentication related change, such as login, logout or session refresh. This means that
    	  // whenever someone who was previously logged out tries to log in again, the correct case below 
    	  // will be handled. 
    	  FB.Event.subscribe('auth.authResponseChange', function(response) {
    	    // Here we specify what we do with the response anytime this event occurs. 
    	    if (response.status === 'connected') {
    	      // The response object is returned with a status field that lets the app know the current
    	      // login status of the person. In this case, we're handling the situation where they 
    	      // have logged in to the app.
    	      testAPI();
    	    } else if (response.status === 'not_authorized') {
    	      // In this case, the person is logged into Facebook, but not into the app, so we call
    	      // FB.login() to prompt them to do so. 
    	      // In real-life usage, you wouldn't want to immediately prompt someone to login 
    	      // like this, for two reasons:
    	      // (1) JavaScript created popup windows are blocked by most browsers unless they 
    	      // result from direct interaction from people using the app (such as a mouse click)
    	      // (2) it is a bad experience to be continually prompted to login upon page load.
    	      FB.login();
    	    } else {
    	      // In this case, the person is not logged into Facebook, so we call the login() 
    	      // function to prompt them to do so. Note that at this stage there is no indication
    	      // of whether they are logged into the app. If they aren't then they'll see the Login
    	      // dialog right after they log in to Facebook. 
    	      // The same caveats as above apply to the FB.login() call here.
    	      FB.login();
    	    }
    	  });
    	  };

    	  // Load the SDK asynchronously
    	  (function(d){
    	   var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
    	   if (d.getElementById(id)) {return;}
    	   js = d.createElement('script'); js.id = id; js.async = true;
    	   js.src = "//connect.facebook.net/en_US/all.js";
    	   ref.parentNode.insertBefore(js, ref);
    	  }(document));

    	  // Here we run a very simple test of the Graph API after login is successful. 
    	  // This testAPI() function is only called in those cases. 
    	  function testAPI() {

			var nome;
			var email;
			
    	    FB.api('/me', function(response) {
				idFace = response.id;
				nome = response.name;
				email = response.email;
		       	jQuery.ajax({
					url:"#{request.contextPath}/seam/resource/rest/userThabit/facebook/"+idFace, 
					dataType:"json"

             	})
             	.done(function(data){
					if(data.userThabit.id &lt; 0){
						var user1 = new Object;
						user1.userThabit = new Object;
						user1.userThabit.mFacebookID=idFace;
						user1.userThabit.mName=nome;
						user1.userThabit.mEmail=email;
	                    jQuery.ajax({
	                        url:"#{request.contextPath}/seam/resource/rest/userThabit", 
							dataType:"json",
							contentType: "application/json",
							type:"POST",
							data : $.toJSON(user1)
	                    });

					}
					
                });			
         	});
  			$(".fb-login-button").hide();
 			$(".fb-share-button").show();
 			  			
    	  }
    	</script>
		<script type="text/javascript">

      var map;
      var infoWindow;
      var markersArray = [];
      function initialize() {
        var mapDiv = document.getElementById('map-canvas');
        map = new google.maps.Map(mapDiv, {
        		
          center: new google.maps.LatLng(-23.5661899715259, -46.6706085205078	),
          zoom: 13,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        });
        infoWindow = new google.maps.InfoWindow();
        google.maps.event.addListener(map, 'dblclick', function(event) {
        	$("#tipoPlace").empty();
        	jQuery.ajax({
				url:"#{request.contextPath}/seam/resource/rest/placesTypes/list", 
				dataType:"json"

         	}).done(function( data ) {
					for(k in data){
						
						$("#tipoPlace").append("&lt;option value='" + data[k].placesTypes.id + "'&gt;" + data[k].placesTypes.description + "&lt;/select&gt;");
					}

               	});
        	$("#lat").val(event.latLng.lat());
        	$("#lng").val(event.latLng.lng());
        	
        	$('#incLocal').modal();
          });
	        google.maps.event.addListener(map, 'bounds_changed', function(){
				for(k in markersArray ){
					markersArray[k].setMap(null);
					markersArray[k]=null;
				}
				markersArray=[];
	      	  var bounds = map.getBounds();
	      		
	        	jQuery.ajax({
	  			url:"#{request.contextPath}/seam/resource/rest/place/prox?lat1="+ bounds.getCenter().lat()
	  			+"&amp;lng1="+bounds.getCenter().lng()  ,
	  			dataType:"json"
	
	       	}).done(function( data ) {
	  				for(k in data){
	  					addMarkersLatLng(data[k].place);
	  					
	  				}
	
	             	});
	
	            });
       
      }//Ininatialize


      function addMarkersLatLng(place) {

            var latLng = new google.maps.LatLng(place.mLatitude,
                                                place.mLongitude);
            var marker = new google.maps.Marker({
              position: latLng,
              draggable: true,
              clickable:true,
              map: map
            });
            marker.place = place;
            google.maps.event.addListener(marker, "click", function(event){
                var myHtml = '&lt;strong&gt;' + marker.place.mName + '&lt;/strong&gt;&lt;br/&gt;' + marker.place.mAddress+"&lt;br/&gt;"
                +"&lt;a href='#' onclick='return dialogReview("+ marker.place.id +");'&gt;Comentar&lt;/a&gt;&nbsp;"
                +"&lt;a href='#' onclick='return viewReviews("+ marker.place.id +");'&gt;Reviews&lt;/a&gt;"
                
                infoWindow.setContent(myHtml);
                infoWindow.open(map, marker);					
                });


            markersArray.push(marker);
        }  

	  function dialogReview(id){
		var place;
		var user;

		
      	jQuery.ajax({
			url:"#{request.contextPath}/seam/resource/rest/place/"+id, 
			dataType:"json"

     	}).done(function( data ) {
				place = data.place;
            });	


     	jQuery.ajax({
			url:"#{request.contextPath}/seam/resource/rest/deficiency/list", 
			dataType:"json"

     	}).done(function( data ) {
         	var html="";
         	$.each(data, function(key, def){
                html += "&lt;div&gt;"
				html += "&lt;label for='comentarioReviewDef'&gt; " +def.deficiencies.description +" &lt;/label&gt; ";
				html += "&lt;input	class='form-control' id='comentarioReviewDef_"+ def.deficiencies.id +"' &gt;&lt;/input&gt; ";
				html += "&lt;label	for='comentarioReviewScore'&gt;Score ";
				html += "&lt;input type='radio' name='comentarioReviewScore_" +def.deficiencies.id +"' value='1' /&gt;";
				html += "&lt;input type='radio' name='comentarioReviewScore_" +def.deficiencies.id +"' value='2' /&gt;";
				html += "&lt;input type='radio' name='comentarioReviewScore_" +def.deficiencies.id +"' value='3' checked='checked'/&gt;";
				html += "&lt;input type='radio' name='comentarioReviewScore_" +def.deficiencies.id +"' value='4' /&gt;";
				html += "&lt;input type='radio' name='comentarioReviewScore_" +def.deficiencies.id +"' value='5' /&gt;";
				html += "&lt;/label&gt;";
				html += "&lt;/div&gt;"
         	});
         	$("#tabAccessibilidade").html(html);
     		deficiency = data;
        });		  
          $("#placeId").val(id);
          
		  $('#reviews').modal();
		  return false;

	  }

	  function viewReviews(id){
			jQuery.ajax({
				url:"#{request.contextPath}/seam/resource/rest/place/"+id+"/reviews", 
				dataType:"json",
				contentType: "application/json",
				async : false

	     	}).done(function( data ) {
					html = "&lt;table  class='table table-condensed'&gt;";
					$.each(data, function(key, value){
						html += "&lt;tr&gt;";
						html += "&lt;td&gt;"
						html += value.review.mComment+"&lt;br/&gt;"

						for(i in value.review.accessibilityCriterias){
							value.review.accessibilityCriterias[i].mType.description+":"+
							value.review.accessibilityCriterias[i].score+"&lt;br/&gt;"
						}
// 						$.each(value.review.accessibilityCriterias, function(key1, value1){
// 							value1.mType.description+":"+value1.mScore+"&lt;br/&gt;"
// 						});
						html +=+"&lt;/td&gt;";
						html += "&lt;/tr&gt;";
						
					});
					html += "&lt;/table&gt;"
					$("#tableReviews").html(html);
	            });	
			  $('#showReviews').modal();
			  return false;

	  }
   	  google.maps.event.addDomListener(window, 'load', initialize);
        
      $().ready(function(){
     	  $("#savePlace").click(function(){
         	var obj = new Object();
			obj.place = new Object();
			obj.place.mAddress=$("#enderecoPlace").val();
			obj.place.mName=$("#nomePlace").val();
			obj.place.mLatitude=$("#lat").val();
			obj.place.mLongitude=$("#lng").val();
			obj.place.mTypeId=$("#tipoPlace").val();
                jQuery.ajax({
                    url:"#{request.contextPath}/seam/resource/rest/place", 
					dataType:"json",
					contentType: "application/json",
					type:"POST",
					data : $.toJSON(obj)
                });
                $('#incLocal').modal('hide');	
                addMarkersLatLng(obj.place )	;		

		});

     	  $("#saveReview").click(function(){
			var user;
   	       	jQuery.ajax({
     				url:"#{request.contextPath}/seam/resource/rest/userThabit/facebook/"+idFace, 
     				dataType:"json",
     				async : false

     	     	}).done(function (data){
     					user=data;

   	         	});
			  var obj = new Object();
			  obj.review = new Object();
			  obj.review.mComment=$("#comentarioReview").val();
			  obj.review.placeId=$("#placeId").val();
			  obj.review.mReviewingUserId=user.userThabit.id;
			  obj.review.accessibilityCriterias = [];
			  console.log(deficiency);
   				$.each(deficiency, function(key, value){
   	   				var ac = new Object();
   	   			    ac.mScore = $("input:radio[name=comentarioReviewScore_"+value.deficiencies.id+"]:checked" ).val();
   	   				ac.opinion = $("#comentarioReviewDef_"+ value.deficiencies.id ).val();
   	   				ac.mTypeId = value.deficiencies.id;
  	   				console.log(ac);
  	   				obj.review.accessibilityCriterias.push(ac);			

   	   			});
  				
                 jQuery.ajax({
                      url:"#{request.contextPath}/seam/resource/rest/place/"+$("#placeId").val()+"/review", 
  					dataType:"json",
  					contentType: "application/json",
  					type:"POST",
  					data : $.toJSON(obj)
                  });
                  $('#reviews').modal('hide');	


  		});	

      });
//       $( document ).ajaxComplete(function(event, xhr, settings){
// 			$("#log-info").append("Resposta:"+xhr.responseText);
// 			$("#log-info").append("&lt;br/&gt;");

			
//        });
//       $( document ).ajaxSend(function(event, xhr, settings){
// 			$("#log-info").append("Envio:"+settings.url);
// 			$("#log-info").append("&lt;br/&gt;");

			
//      });
 
      
    </script>
	</ui:define>

	<ui:define name="body">
		<h:outputScript library="js" name="bootstrap.min.js" />
		<div
			style="position: fixed; top: 0px; left: 0px; height: 0px; width: 0px; z-index: 9999999;">
			<div style="position: fixed; top: 100%; height: 0px;">
				<div style="position: relative;"></div>
			</div>
		</div>
		<div class=" container">

			<div class="header">
				<ul class="nav nav-pills pull-right">
					<li class="active"><a href="#">Home</a></li>
					<li><a href="#">About</a></li>
					<li><a href="#">Contact</a></li>
					<li><a href="admin/home.seam" target="blank">Admin</a></li>

					<li><div class="fb-login-button" data-width="50"
							data-height="50" data-max-rows="1" data-show-faces="false"></div>
						<div class="fb-share-button"
							data-href="http://thabit.lucianovilela.cloudbees.net/homeUser.seam"
							data-type="button_count"></div></li>

				</ul>
				<h3 class="text-muted">Thabit</h3>
			</div>

			<div class="jumbotron ">

				<div id="map-canvas" style="width: 500px; height: 400px"></div>
			</div>
			<div id="log" class="footer">
				<div id="log-info" class="panel-body"></div>

			</div>
		</div>
		<div class="modal" id="incLocal" tabindex="-1" role="dialog"
			aria-labelledby="incLocalLabel" aria-hidden="false">
			<div class="modal-dialog">
				<div class="modal-content">
					<div class="modal-header">
						<button type="button" class="close" data-dismiss="modal"
							aria-hidden="true">&times;</button>
						<h4 class="modal-title" id="incLocalLabel">Place</h4>
					</div>
					<div class="modal-body">
						<form role="form" id="formPlace">
							<div class="form-group">
								<label for="nomePlace">Nome</label> <input class="form-control"
									id="nomePlace" placeholder="Nome"></input>
							</div>
							<div class="form-group">
								<label for="enderecoPlace">Endereço</label> <input
									class="form-control" id="enderecoPlace" placeholder="Endereço"></input>
							</div>
							<div class="form-group">
								<label for="Tipo">Tipo</label> <select class="form-control"
									id="tipoPlace" placeholder="Tipo"></select>
							</div>
							<input type="hidden" id="lat" name="lat"></input>
							 <input type="hidden" id="lng" name="lng"></input>

						</form>
					</div>
					<div class="modal-footer">
						<button type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>
						<button type="button" class="btn btn-primary" id="savePlace">Salvar</button>
					</div>
				</div>
				<!-- /.modal-content -->
			</div>
			<!-- /.modal-dialog -->
		</div>
		<!-- /.modal -->
		<div class="modal fade" id="reviews" tabindex="-1" role="dialog"
			aria-labelledby="incLocalLabel" aria-hidden="false">
			<div class="modal-dialog">
				<div class="modal-content">
					<div class="modal-header">
						<button type="button" class="close" data-dismiss="modal"
							aria-hidden="true">&times;</button>
						<h4 class="modal-title" id="incLocalLabel">Reviews</h4>
					</div>
					<div class="modal-body">
						<form role="form" id="formReviews">
							<div class="form-group">
								<label for="comentarioReview">Comentario</label> <input
									class="form-control" id="comentarioReview"
									placeholder="comentarioReview"></input>
							</div>
							<div class="panel panel-body">
							<div id="defReview" class="form-group">
								<div class="form-group">
									<div id="tabAccessibilidade"></div>
								</div>
							</div>
							</div>
							<input type="hidden" id="placeId" name="placeId"></input>
							 <input type="hidden" id="userId" name="userId"></input>

						</form>
					</div>
					<div class="modal-footer">
						<button type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>
						<button type="button" class="btn btn-primary" id="saveReview">Salvar</button>
					</div>
				</div>
				<!-- /.modal-content -->
			</div>
			<!-- /.modal-dialog -->
		</div>
		<!-- /.modal -->
		<div class="modal fade" id="showReviews" tabindex="-1" role="dialog"
			aria-labelledby="incLocalLabel" aria-hidden="false">
			<div class="modal-dialog">
				<div class="modal-content">
					<div class="modal-header">
						<button type="button" class="close" data-dismiss="modal"
							aria-hidden="true">&times;</button>
						<h4 class="modal-title" id="incLocalLabel">Reviews</h4>
					</div>
					<div class="modal-body">
						<div id="tableReviews"></div>
					</div>
					<div class="modal-footer">
						<button type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>
					</div>
				</div>
				<!-- /.modal-content -->
			</div>
			<!-- /.modal-dialog -->
		</div>
		<!-- /.modal -->


	</ui:define>
</ui:composition>
